package com.yhc.my.an_meishia.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.yhc.my.an_meishia.R;
import com.yhc.my.an_meishia.activities.MedioActivity;
import com.yhc.my.an_meishia.adapters.HotAdapter;
import com.yhc.my.an_meishia.bean.HotShows;
import com.yhc.my.an_meishia.utils.HttpUtil;
import com.yhc.my.an_meishia.utils.PATH;

import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 */
public class HotFragment extends Fragment {
    int count  = 5;
    int page = 1;
    private List<HotShows> list;
    private String path;
//    StringBuilder sb = new StringBuilder();
//    final String path = sb.append(Contasts.BASE_URL).append(Contasts.CATEGOTY_URL).toString();

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            list  = (List<HotShows>) msg.obj;
            HotAdapter adapter = new HotAdapter(getActivity(),getContext(),list);
                    grid.setAdapter(adapter);
                    adapter.notifyDataSetChanged();




        }
    };
    private PullToRefreshGridView mPull;

    public static HotFragment createFragment(int position) {
        HotFragment fragment = new HotFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("position", position);
        fragment.setArguments(bundle);
        return fragment;
    }

    private GridView grid;

    public HotFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_hot, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mPull = (PullToRefreshGridView) view.findViewById(R.id.gv);
       grid = mPull.getRefreshableView();
        grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), MedioActivity.class);
                HotShows ho = (HotShows) parent.getItemAtPosition(position);
                if (ho.getMedia()!=null){
                    String video = ho.getMedia().getVideo();
                    if (video!=null){
                        String caption = ho.getMedia().getCaption();
                        intent.putExtra("video",video);
                        intent.putExtra("caption",caption);
                        startActivity(intent);
                    }else {
                        Toast.makeText(getActivity(),"视频资源不存在",Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Toast.makeText(getActivity(),"视频资源不存在",Toast.LENGTH_SHORT).show();
                }
            }
        });
        new Thread() {
            @Override
            public void run() {
                Message msg = Message.obtain();
                msg.what = 1;
                Bundle bundle = getArguments();
                path = bundle.getString("pos");
                byte[] date = HttpUtil.loadData(path);
                String str = new String(date);
                list = JSON.parseArray(str, HotShows.class);
                msg.obj = list;
                handler.sendMessage(msg);
            }
        }.start();
        loadListener();


    }

   public void loadListener(){
       //设置下拉模式
    mPull.setMode(PullToRefreshBase.Mode.BOTH);
       mPull.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
           @Override
           public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                final String s2;
               //刷新时间
               String label = DateUtils.formatDateTime(
                       getContext(), System.currentTimeMillis(),
                       DateUtils.FORMAT_SHOW_TIME
                               | DateUtils.FORMAT_SHOW_DATE
                               | DateUtils.FORMAT_ABBREV_ALL
               );
               refreshView.getLoadingLayoutProxy()
                       .setLastUpdatedLabel(label);
               StringBuilder builder = new StringBuilder();
               final String s = builder.append(path).append(PATH.str).toString();
               int count1= 10;
               String s1 = Integer.toString(count1);
               s2 = s.replaceAll("%d", s1);

                   new Thread() {
                       @Override
                       public void run() {
                           byte[] date = HttpUtil.loadData(s2);
                           String str = new String(date);
                           list = JSON.parseArray(str, HotShows.class);
                          Message msg = Message.obtain();
                           msg.obj = list;
                           handler.sendMessage(msg);
                       }
                   }.start();
               mPull.onRefreshComplete();//停止刷新操作

           }

           @Override
           public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
               final String s2;
               //刷新时间
               String label = DateUtils.formatDateTime(
                       getContext(), System.currentTimeMillis(),
                       DateUtils.FORMAT_SHOW_TIME
                               | DateUtils.FORMAT_SHOW_DATE
                               | DateUtils.FORMAT_ABBREV_ALL
               );
               refreshView.getLoadingLayoutProxy()
                       .setLastUpdatedLabel(label);
               StringBuilder builder = new StringBuilder();
               final String s = builder.append(path).append(PATH.str).toString();
               Log.i("TAG", "----------------- "+page);
                  count+=10;
                  page=+1;
                  Log.e("TGA", "刷新了" + s);
                  String s1 = Integer.toString(count);
                  s2 = s.replaceAll("%d", s1);
                  if (page <= 20) {
                      new Thread() {
                          @Override
                          public void run() {
                              byte[] date = HttpUtil.loadData(s2);
                              String str = new String(date);
                              list = JSON.parseArray(str, HotShows.class);
                              Message msg = Message.obtain();
                              msg.obj = list;
                              handler.sendMessage(msg);
                          }
                      }.start();
                  } else {
                      Toast.makeText(getActivity(), "没有更多数据了", Toast.LENGTH_SHORT).show();
                  }
                  mPull.onRefreshComplete();//停止刷新操作
              }

       });
   }

//    private void loadUrl() {
//       new Thread(){
//           @Override
//           public void run() {
//               int page = 1;
//               page +=3;
//               Bundle bundle = getArguments();
//               String path = bundle.getString("pos");
//               StringBuilder builder = new StringBuilder();
//               String s = builder.append(path).append(PATH.str).toString();
//               String s1 = Integer.toString(page);
//               String s2 = s.replaceAll("%d", s1);
//               Log.i("TAG", "----------------- s2"+s2);
//               byte[] date = HttpUtil.loadData(s2);
//               String str = new String(date);
//               list = JSON.parseArray(str, HotShows.class);
//           }
//       }.start();
//    }


}
